package com.tianji.remark.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author xzh
 * @since 2024-03-16
 */
//@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_={@Lazy} )
public class LikedRecordServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {

    private final RabbitMqHelper mqHelper;


    /**
     * 增加或取消点赞
     */

    @Override
    @Transactional
    public void addLikeRecord(LikeRecordFormDTO likeRecordFormDTO) {
        //1.先根据liked判断是点赞还是取消点赞
        Long userId = UserContext.getUser();
        if (likeRecordFormDTO.getLiked()){
            //2.根据用户id和bizId 查询用户有没有给此业务点赞  返回数字
            Integer count = lambdaQuery().eq(LikedRecord::getUserId, userId)
                    .eq(LikedRecord::getBizId, likeRecordFormDTO.getBizId())
                    .count();
            //2.1若返回的为1 则证明用户点过赞了 直接返回
            if (count==1){
                return;
            }
            //2.2若返回0则用户没有点过赞 新增点赞记录 并通过mq通知 增加点赞总量
            //新增点赞记录
            LikedRecord likedRecord=new LikedRecord();
            likedRecord.setBizId(likeRecordFormDTO.getBizId());
            likedRecord.setUserId(userId);
            likedRecord.setBizType(likeRecordFormDTO.getBizType());
            save(likedRecord);

            //执行成功统计数量
            Integer likedTimes = lambdaQuery()
                    .eq(LikedRecord::getBizId, likeRecordFormDTO.getBizId()).count();
            //发mq消息
            mqHelper.send(
                    LIKE_RECORD_EXCHANGE,
                    StringUtils.format(LIKED_TIMES_KEY_TEMPLATE,likeRecordFormDTO.getBizType()),
                    new  LikedTimesDTO(likeRecordFormDTO.getBizId(), likedTimes)
            );
        }
        //3.若是取消则直接删除
        boolean remove = remove(new QueryWrapper<LikedRecord>().lambda().eq(LikedRecord::getUserId, userId)
                .eq(LikedRecord::getBizId, likeRecordFormDTO.getBizId()));
        if (!remove){
            //3.1若删除失败 则证明没有点过赞 取消失败直接返回
            return;
        }
        //3.2若删除成功则通过mq异步通知 减少总点赞数
        Integer likedTimes = lambdaQuery()
                .eq(LikedRecord::getBizId, likeRecordFormDTO.getBizId()).count();

        mqHelper.send(LIKE_RECORD_EXCHANGE,
                StringUtils.format(LIKED_TIMES_KEY_TEMPLATE,likeRecordFormDTO.getBizType()),
                new LikedTimesDTO(likeRecordFormDTO.getBizId(),likedTimes));
    }



    /**
     * 查询用户是否对某个业务点赞
     * @param bizIds
     * @return
     */
    @Override
    public Set<Long> isBizLiked(List<Long> bizIds) {
        // 逻辑: 将用户已经点赞的业务id返回
        Long userId = UserContext.getUser();

        // 获得bizIds里的所有信息
        List<LikedRecord> list = lambdaQuery().eq(LikedRecord::getUserId, userId)
                .in(CollUtils.isEmpty(bizIds), LikedRecord::getBizId, bizIds)
                .list();
        // 没有点赞的则直接返回
        if (CollUtils.isEmpty(list)){
            return null;
        }

        // 提取set集合
        Set<Long> set = list.stream().map(LikedRecord::getBizId).collect(Collectors.toSet());
        return set;
    }

    @Override
    public void readLikedTimesAndSentMessages(String bizType, int maxBizSize) {
        return;
    }
}
